//Create by zhongxiang.huang
$(function () {
    
    $MB.initTpvMeetingElement();
    $("#input-file").prop("accept",".zip")
    
    $('.j-tpv-tab li').click(function() {
        var old = $('.j-tpv-tab li.active').data('tab');
        var current = $(this).data('tab');
        if (current != old) {
            $(this).addClass('active').siblings('li').removeClass('active');
            $('div[data-tab="'+ old +'"]').hide();
            $('div[data-tab="'+ current +'"]').show();
            $('#'+old).hide();
            $('#'+current).show();
        }
    });

    $(".tpv-nav-item:first").addClass("active");

        
    var settingsLocal = {
        url: ctx + "appupdate/list/4",
        pageSize: 10,
        clickToSelect: false,
        queryParams: function (params) {
            var startDate =$("input[name='local-plugin-filter-start-date-link']").val();
            var endDate = $("input[name='local-plugin-filter-end-date-link']").val();

            var hasStartDateSelected = startDate != '';
            var hasEndDateSelected = endDate != '';

            return {
                pageSize: params.limit,
                pageNum: params.offset / params.limit + 1,
                startDate: (hasStartDateSelected ? new Date(startDate) : undefined),
                endDate: (hasEndDateSelected ? new Date(endDate) : undefined),
            };
        },
        columns: [{
            checkbox: true
        }, {
            field: 'id',
            visible: false
        }, {
            field: 'name',
            title: 'name',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }
        }, {
            field: 'versionCode',
            title: 'versionCode',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }
        },{
            field: 'fileSize',
            title: 'fileSize',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }            
        }, {
            field: 'publishTime',
            title: 'publishTime',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }            
        }, {
            field: 'downPath',
            title: 'downPath',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }            
        }]
    };

    $MB.initTable('browserPluginLocalTable', settingsLocal);
    
    var settingsLine = {
        url: ctx + "appupdate/list/5",
        pageSize: 10,
        clickToSelect: false,
        queryParams: function (params) {
            var startDate =$("input[name='line-plugin-filter-start-date-link']").val();
            var endDate = $("input[name='line-plugin-filter-end-date-link']").val();

            var hasStartDateSelected = startDate != '';
            var hasEndDateSelected = endDate != '';

            return {
                pageSize: params.limit,
                pageNum: params.offset / params.limit + 1,
                startDate: (hasStartDateSelected ? new Date(startDate) : undefined),
                endDate: (hasEndDateSelected ? new Date(endDate) : undefined),
            };
        },
        columns: [{
            checkbox: true
        }, {
            field: 'id',
            visible: false
        }, {
            field: 'name',
            title: 'name',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }
        }, {
            field: 'versionCode',
            title: 'versionCode',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }
        }, {
            field: 'publishTime',
            title: 'publishTime',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }            
        }, {
            field: 'downPath',
            title: 'downPath',
            cellStyle: {
                css: {                    
                    'text-align':'center',
                }
            }            
        }]
    };

    $MB.initTable('browserPluginLineTable', settingsLine);

    $("#file-upload .start-upload").click(function () {
    	var inputfile = document.getElementById("input-file").files;
    	var fileName = inputfile[0].name;
    	var ext = fileName.slice(fileName.lastIndexOf(".")+1).toLowerCase();
    	if("zip" === ext){
    		$("#result").text("正在上传");
    		var form = $('#fileUploadForm')[0];
    	    var data = new FormData(form);
    	    $.ajax({
    	        type: "POST",
    	        enctype: 'multipart/form-data',
    	        url: "appupdate/upload",
    	        data: data,
    	        //http://api.jquery.com/jQuery.ajax/
    	        //http://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
    	        processData: false, //prevent jQuery from automatically transforming the data into a query string
    	        contentType: false,
    	        cache: false,
    	        timeout: 600000,
    	        success: function (data) {

    	        	$("#result").text(data.msg);
    	        	$("#file-infor").show();
	 	            $("#version-code").val("");
	 	            $("#package-name").val("");
    	        },
    	        error: function (e) {

    	            $("#result").text(e.responseText);
    	            console.log("ERROR : ", e);
    	        }
    	    });
    	}else{
    		$("#result").text("文件类型不正确");
    	}        
   });
	
	$("#file-upload .finish").click(function () {
		var inputfile = document.getElementById("input-file").files;	
		var versionCode = $("input[name='versionCode']").val();
		var publishStatus = $("select[name='publishStatus']").val();
		var data = {
            "name": inputfile[0].name,
            "fileSize":formatFileSize(inputfile[0].size),
            "fileType":4,
            "versionCode":versionCode,
            "publishStatus":publishStatus
        };

		$(this).attr("disabled",true);
        $.post(ctx + "appupdate/add", data, function (r) {
            if (r.code === 0) {
                closeModal();
                $MB.n_success(r.msg);
                $MB.refreshTable("browserPluginLocalTable");
            } else {
                $MB.n_danger(r.msg);
            }
            $("#file-upload .finish").removeAttr("disabled");
        });
       
	});
	
	$("#line-plugin-add .finish").click(function () {
		var name = $("#name-line-plugin").val();
		var downPath = $("#down-path--line-plugin").val();
		var versionCode = $("#version-code-line-plugin").val();
		var publishStatus = $("#publish-status-line-plugin").val();		
		var data = {
            "name": name,
            "downPath":downPath,
            "versionCode":versionCode,
            "publishStatus":publishStatus,
            "fileType":5
        };

		$(this).attr("disabled",true);
        $.post(ctx + "appupdate/add", data, function (r) {
            if (r.code === 0) {
            	$("#line-plugin-add .finish").removeAttr("disabled");
                $MB.closeAndRestModal("line-plugin-add");
                $MB.n_success(r.msg);
                $MB.refreshTable("browserPluginLineTable");
            } else {
                $MB.n_danger(r.msg);
            }
            $("#line-plugin-add .finish").removeAttr("disabled");
        });
       
	});
	
	$("#plugin-edit .finish").click(function () {
		var appId = $("#pluginEditForm").attr("app-id");
		var versionCode = $("#edit-version-code").val();
		$(this).attr("disabled",true);
		
		var data = {
			"fileType":4,
            "versionCode": versionCode
        };
		
		$.post(ctx + "appupdate/edit/" + appId, data, function (r) {
            if (r.code === 0) {
            	$MB.closeAndRestModal("plugin-edit");
            	$("#plugin-edit .finish").removeAttr("disabled");
                $MB.n_success(r.msg);
                $MB.refreshTable("browserPluginLocalTable");
            } else {
                $MB.n_danger(r.msg);
            }
            	
            $("#plugin-edit .finish").removeAttr("disabled");
        });
	});
	
	$("#line-plugin-edit .finish").click(function () {
		var appId = $("#linePluginEditForm").attr("app-id");
		var name = $("#edit-name-line").val();
		var downPath = $("#edit-down-path-line").val();
		var versionCode = $("#edit-version-code-line").val();
		$(this).attr("disabled",true);
		
		var data = {
			"fileType":5,
            "name": name,
            "downPath": downPath,
            "versionCode": versionCode
        };
		writeObj(data);
		$.post(ctx + "appupdate/edit/" + appId, data, function (r) {
            if (r.code === 0) {
            	$MB.closeAndRestModal("line-plugin-edit");
            	$("#line-plugin-edit .finish").removeAttr("disabled");
                $MB.n_success(r.msg);
                $MB.refreshTable("browserPluginLineTable");
            } else {
                $MB.n_danger(r.msg);
            }
            	
            $("#line-plugin-edit .finish").removeAttr("disabled");
        });
	});
	
	$("#local-plugin-filter-start-date").on("change", searchLocal);
    $("#local-plugin-filter-end-date").on("change", searchLocal);
    $("#line-plugin-filter-start-date").on("change", searchLine);
    $("#line-plugin-filter-end-date").on("change", searchLine);
});



function addLocalNewVersion(){
	var $form = $('#file-upload');
    $form.modal();
}

function addLineNewVersion(){
	var $form = $('#line-plugin-add');
    $form.modal();
}

function editLocalPlugin() {
    var selected = $("#browserPluginLocalTable").bootstrapTable('getSelections');
    var selected_length = selected.length;

    if(!selected_length) {
        $MB.n_warning("请选择要编辑的应用");
        return;
    }
    if(selected_length > 1) {
        $MB.n_warning("只支持单个应用编辑");
        return;
    }

    doEtitLocalPlugin(selected[0].id);
}

function doEtitLocalPlugin(appId){
	$.get(ctx + "appupdate/edit/" + appId, function(r) {
        if(r.code == 0) { 
        	var app = r.msg;

            $pluginEditForm = $("#pluginEditForm")
            $pluginEditForm.attr("app-id", app.id);
            $("#edit-version-code").val(app.versionCode);
            $('#plugin-edit').modal();
        } else {
            $MB.n_danger(r.msg);
        }
    });
}

function editLinePlugin() {
    var selected = $("#browserPluginLineTable").bootstrapTable('getSelections');
    var selected_length = selected.length;

    if(!selected_length) {
        $MB.n_warning("请选择要编辑的应用");
        return;
    }
    if(selected_length > 1) {
        $MB.n_warning("只支持单个应用编辑");
        return;
    }

    doEtitLinePlugin(selected[0].id);
}

function doEtitLinePlugin(appId){
	$.get(ctx + "appupdate/edit/" + appId, function(r) {
        if(r.code == 0) { 
        	var app = r.msg;

            $linePluginEditForm = $("#linePluginEditForm")
            $linePluginEditForm.attr("app-id", app.id);
            
            $("#edit-name-line").val(app.name);
            $("#edit-version-code-line").val(app.versionCode);
            $("#edit-down-path-line").val(app.downPath);
            
            $('#line-plugin-edit').modal();
        } else {
            $MB.n_danger(r.msg);
        }
    });
}


function searchLocal() {
    $MB.refreshTable('browserPluginLocalTable');
}
function searchLine() {
    $MB.refreshTable('browserPluginLineTable');
}

function refreshLocalPlugin() {
    $(".local-plugin-table-form input[type=hidden]").val('');
    $(".local-plugin-table-form")[0].reset();

    $MB.refreshTable('browserPluginLocalTable');
}

function refreshLinePlugin() {
    $(".line-plugin-table-form input[type=hidden]").val('');
    $(".line-plugin-table-form")[0].reset();

    $MB.refreshTable('browserPluginLineTable');
}

function closeModal() {
	$("#input-file").val('');
	$("#result").text("");
	$("#file-infor").hide();
    $("#file-upload .finish").removeAttr("disabled");
    $MB.closeAndRestModal("file-upload");
}

function formatFileSize(fileSize) {
    if (fileSize < 1024) {
        return fileSize + 'B';
    } else if (fileSize < (1024*1024)) {
        var temp = fileSize / 1024;
        temp = temp.toFixed(2);
        return temp + 'KB';
    } else if (fileSize < (1024*1024*1024)) {
        var temp = fileSize / (1024*1024);
        temp = temp.toFixed(2);
        return temp + 'MB';
    } else {
        var temp = fileSize / (1024*1024*1024);
        temp = temp.toFixed(2);
        return temp + 'GB';
    }
}


